package node.decl;

import grammar.Lexer;
import lexical.Key;
import node.Node;
import node.exp.Exp;
import symbol.SymbolTable;

import java.util.ArrayList;

public class InitVal implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private Exp exp;
    private ArrayList<InitVal> initVals = new ArrayList<>();
    public ArrayList<Node> nodes = new ArrayList<>();

    public InitVal(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseInitVal();
    }

    private void parseInitVal() {
        if (!lexer.isWordType(0, Key.LBRACE)) {
            exp = new Exp(lexer, table, this);
            nodes.add(exp);
        } else {
            nodes.add(lexer.getCurWord()); // {
            InitVal initVal;
            if (!lexer.isWordType(0, Key.RBRACE)) {
                initVal = new InitVal(lexer, table, this);
                nodes.add(initVal);
                initVals.add(initVal);
                while (lexer.isWordType(0, Key.COMMA)) {
                    nodes.add(lexer.getCurWord()); // ,
                    initVal = new InitVal(lexer, table, this);
                    nodes.add(initVal);
                    initVals.add(initVal);
                }
            }
            nodes.add(lexer.getCurWord()); // }
        }
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<InitVal>\n").toString();
    }

    @Override
    public String genMidCode() {
        return exp.genMidCode();
    }

    public ArrayList<InitVal> getInitVals() {
        ArrayList<InitVal> ret = new ArrayList<>();
        for (Node node : nodes) {
            if (node instanceof InitVal) {
                ret.add((InitVal) node);
            }
        }
        return ret;
    }

    public int getValue_0() {
        return exp.getValue();
    }

    public ArrayList<Integer> getValue_1() {
        ArrayList<Integer> val_1 = new ArrayList<>();
        for (InitVal initVal : initVals) {
            val_1.add(initVal.getValue_0());
        }
        return val_1;
    }

    public ArrayList<ArrayList<Integer>> getValue_2() {
        ArrayList<ArrayList<Integer>> val_2 = new ArrayList<>();
        for (InitVal initVal : initVals) {
            val_2.add(initVal.getValue_1());
        }
        return val_2;
    }
}
